package com.xopencode.io;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;

/**
 * @author Mcb
 * @date 2022/5/2
 * @apiNote 通过nio创建文件
 */
public class ChannelWriteTest {
    public static void main(String[] args) throws IOException {
        String fileName = "NioTest.txt";
        FileOutputStream fis = new FileOutputStream(fileName);
        FileChannel channel = fis.getChannel();
        //创建缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        buffer.put("Hello word,中文测试!!".getBytes(StandardCharsets.UTF_8));
        buffer.flip(); //注意将缓冲区从写转换成读，position设置到0，通道开始读取
        int result = channel.write(buffer);
        System.out.println(result);
        fis.close();
    }
}
